package com.platform.api;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.platform.exception.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NoArgsConstructor;

import java.text.MessageFormat;

/**
 * Response基类
 */

@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Response<T> extends BaseDto {
    /**
     * 错误码及错误信息
     */
    private Status status = new Status();

    /**
     * 数据承载字段
     */
    @JsonInclude(value = JsonInclude.Include.NON_NULL)
    private T data;

    /**
     * 分页数据
     */
    @JsonInclude(value = JsonInclude.Include.NON_NULL)
    private Page page;

    public Status getStatus() {
        return status;
    }

    public void setStatus(Status status) {
        this.status = status;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public Page getPage() {
        return page;
    }

    public void setPage(Page page) {
        this.page = page;
    }

    @JsonIgnore
    public boolean isSuccess() {
        return  SysError.SUCCESS.getCode().equals(this.getStatus().getCode());
    }

    public static Response failure(IErrorCode errorCode) {
        return Response.builder()
                .status(new Status(errorCode))
                .build();
    }

    public static Response failure(IErrorCode errorCode, Object... args) {
        return Response.builder()
                .status(new Status(errorCode.getCode(), MessageFormat.format(errorCode.getMsg(), args)))
                .build();
    }

    public static Response failure(ApplicationException exception) {
        return Response.builder()
                .status(new Status(exception.getCode(), exception.getMsg()))
                .build();
    }

    public static Response failure(BusinessException exception) {
        return Response.builder()
                .status(new Status(exception.getCode(), exception.getMsg()))
                .build();
    }

    public static Response failure(SystemException exception) {
        return Response.builder()
                .status(new Status(exception.getCode(), exception.getMsg()))
                .build();
    }

    public static Response defaultFallback() {
        return failure(SysError.UNKNOWN);
    }

    public static <T> Response<T> success() {
        return success(null, null);
    }

    public static <T> Response<T> success(T data) {
        return success(data, null);
    }

    public static <T> Response<T> success(T data, Page page) {
        return Response.<T>builder()
                .data(data)
                .page(page)
                .status(new Status(SysError.SUCCESS))
                .build();
    }
}
